import {
  getActivityProductInfoList,
  getActivitySessionList,
  pageQuery,
  PageQueryResultPageItem,
  RegidtrationProductActivityOptions,
  submitRegidtrationProductActivity,
} from '@/api/temu';
import { toast } from 'sonner';
import { concurrentLimit, delay } from './utils';

export interface TemuProduct {
  skuInfo: string;
  temuStock: number;
  temuPrice: number;
  productId: number;
  skcId: number;
  skcInfo: string;
  skuId: number;
  productCreateAt: number;
}

function initPageItem(pageItem: PageQueryResultPageItem): TemuProduct {
  const skuInfo = pageItem.productSkuSummaries[0]?.extCode || '';
  let temuStock = pageItem.productSkuSummaries[0]?.productSkuSemiManagedStock.skuStockQuantity;
  // 因为可能会等于 0
  if (temuStock === undefined || temuStock === null) {
    temuStock = NaN;
  }
  let temuPrice = pageItem.productSkuSummaries[0]?.siteSupplierPrices[0]?.supplierPrice;
  // 因为可能会等于 0
  if (temuPrice === undefined || temuPrice === null) {
    temuPrice = NaN;
  }
  const productId = pageItem.productId || NaN;
  const skcId = pageItem.productSkcId || NaN;
  const skcInfo = pageItem.extCode || '';
  // skuId 不可能等于 0
  const skuId = pageItem.productSkuSummaries[0]?.productSkuId || NaN;

  const productCreateAt = pageItem.createdAt;

  return {
    skuInfo,
    temuStock,
    temuPrice,
    productId,
    skcId,
    skcInfo,
    skuId,
    productCreateAt,
  };
}

// 通过 MallId 来获取对应的产品信息
export async function getTemuTotalProductByMallId({
  mallId,
  pageSize,
  status,
  obtainedTotalPageSize,
}: {
  mallId: number;
  pageSize: number;
  status: number;
  obtainedTotalPageSize: (totalPageSize: number) => void;
}) {
  const totalPageItems: PageQueryResultPageItem[] = [];
  // 先进行第一页的获取
  const pageFirstQuery = await pageQuery(
    {
      page: 1,
      pageSize,
      skcTopStatus: status,
    },
    mallId,
  );
  if (!pageFirstQuery.success) {
    throw new Error(`获取第一页数据失败: ${pageFirstQuery.errorMsg}`);
  }
  const total = pageFirstQuery.result.total;
  obtainedTotalPageSize(total);
  const pageItems = pageFirstQuery.result.pageItems;
  totalPageItems.push(...pageItems);
  toast.info(`获取到 ${totalPageItems.length} 个商品`);
  const pageCount = Math.ceil(total / pageSize);
  await concurrentLimit(
    Array.from({ length: pageCount - 1 }).map((_, index) => {
      return async () => {
        const pageQueryResult = await pageQuery(
          {
            page: index + 2,
            pageSize,
            skcTopStatus: status,
          },
          mallId,
        );
        if (!pageQueryResult.success) {
          throw new Error(`获取第${index + 2}页数据失败: ${pageQueryResult.errorMsg}`);
        }
        const pageItems = pageQueryResult.result.pageItems;
        totalPageItems.push(...pageItems);
        toast.info(`获取到 ${totalPageItems.length} 个商品基础信息`);
      };
    }),
  );

  const temuTotalProduct = totalPageItems.map((pageItem) => {
    return initPageItem(pageItem);
  });
  return temuTotalProduct;
}

// 通过产品的 ids 来获取产品的信息
export async function getTemuTotalProductByProductIds({
  mallId,
  productIds,
}: {
  mallId: number;
  productIds: number[];
}) {
  // 先进行第一页的获取
  const pageQueryResult = await pageQuery(
    {
      page: 1,
      pageSize: productIds.length,
      productIds: productIds,
    },
    mallId,
  );

  if (!pageQueryResult.success) {
    throw new Error(`${pageQueryResult.errorMsg}`);
  }
  const pageItems = pageQueryResult.result.pageItems;

  const temuTotalProduct = pageItems.map((pageItem) => {
    return initPageItem(pageItem);
  });
  return temuTotalProduct;
}

// 根据 mallId 获取对应活动的所有产品信息
export interface ActivityProductInfo {
  suggestActivityPrice: number;
  suggestActivityStock: number;
  productId: number;
  skuId: number;
  skcId: number;
  skuInfo: string;
  sessionIds: number[];
}
export async function getTotalActivityProductInfoList({
  activityType,
  activityThematicId,
  mallId,
}: {
  activityType: number;
  activityThematicId?: number;
  mallId: number;
}) {
  const activityProductInfoList: ActivityProductInfo[] = [];
  let total = 0;
  async function getBatchActivityProductInfoList(searchScrollContext?: string) {
    const rowCount = 50;
    const getActivityProductInfoListResult = await getActivityProductInfoList({
      activityThematicId,
      activityType,
      rowCount,
      searchScrollContext,
      mallId,
    });
    if (getActivityProductInfoListResult.success) {
      const searchScrollContext = getActivityProductInfoListResult.result.searchScrollContext;
      const matchList = getActivityProductInfoListResult.result.matchList;
      const productIds = matchList.map((match) => match.productId);
      // 获取场次信息
      const sessionList = await getActivitySessionList({
        activityType,
        activityThematicId,
        productIds,
        mallId,
      });
      // console.log(sessionList);
      if (sessionList.success) {
        matchList.forEach((match) => {
          const skuList = match.activitySiteInfoList[0].skcList[0].skuList;
          activityProductInfoList.push({
            // 建议活动库存可能是建议库存加上目标库存
            suggestActivityStock: match.suggestActivityStock,
            suggestActivityPrice: skuList[0].suggestActivityPrice,
            skuId: skuList[0].skuId,
            skuInfo: skuList[0].extCode,
            skcId: match.activitySiteInfoList[0].skcList[0].skcId,
            productId: match.productId,
            sessionIds: sessionList.result.productCanEnrollSessionMap[match.productId].map(
              (session) => session.sessionId,
            ),
          });
        });
        total += matchList.length;
        toast.info(`成功获取 ${total} 条活动建议信息`, {
          position: 'top-right',
        });
        if (searchScrollContext) {
          const info = JSON.parse(atob(searchScrollContext)) as any;
          if (info.hasMore) {
            await getBatchActivityProductInfoList(searchScrollContext);
          }
        }
      } else {
        // productIds 为空时会有这样的错误,这样的错误表明获取不到活动信息
        if (sessionList.errorCode === 3000000) {
          toast.error(`没有产品符合活动条件`, {
            position: 'top-right',
          });
          return activityProductInfoList;
        }
        throw new Error(`获取活动建议信息时失败: ${sessionList.errorMsg}`);
      }
    } else {
      throw new Error(`获取活动建议信息时失败: ${getActivityProductInfoListResult.errorMsg}`);
    }
  }

  await getBatchActivityProductInfoList();

  return activityProductInfoList;
}

// 活动报名
// 11 表示已经报名
// "errorCode":2000000 表示操作过快
enum FailReason {
  ENROLL_SESSION_HAS_ATTEND = 11,
}
export async function regidtrationProductActivity(
  regidtrationProductActivityOptions: RegidtrationProductActivityOptions,
) {
  const regidtrationResult = await submitRegidtrationProductActivity(
    regidtrationProductActivityOptions,
  );
  if (regidtrationResult.success) {
    const failCount = regidtrationResult.result.failCount;
    if (failCount > 0) {
      const fail = regidtrationResult.result.failList[0];
      if (fail.failReason === FailReason.ENROLL_SESSION_HAS_ATTEND) {
        return {
          successMessage: `活动已经曾经报过名(${fail.failMsg})`,
        };
      }
      throw new Error(regidtrationResult.result.failList[0].failMsg);
    }
  } else {
    // 如果操作过快那么延迟一定时间后重新报名
    if (regidtrationResult.errorCode === 2000000) {
      await delay(500);
      return await regidtrationProductActivity(regidtrationProductActivityOptions);
    } else {
      throw new Error(regidtrationResult.errorMsg || '');
    }
  }
  return {
    successMessage: '活动报名完成',
  };
}
